<template>
  <h1>新用户注册</h1>
  <el-form  ref="refUserForm"  :rules="formRules" class="user-form" :model="user" label-width="120px">
    <el-form-item label="用户名"  prop="name" :rules="formRules.isNotNull('不能为空')">
      <el-input v-model="user.name" />
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="user.sex">
        <el-radio label="男" value="男"/>
        <el-radio label="女" value="女"/>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="地区">
      <el-select v-model="user.addr" placeholder="请选择你的地区">
        <el-option label="上海" value="上海" />
        <el-option label="北京" value="北京" />
      </el-select>
    </el-form-item>
    <el-form-item label="爱好">
      <el-checkbox-group v-model="user.hobby">
        <el-checkbox label="篮球" name="type" />
        <el-checkbox label="羽毛球" name="type" />
        <el-checkbox label="足球" name="type" />
        <el-checkbox label="网球" name="type" />
      </el-checkbox-group>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(refUserForm)">注册</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">

import {reactive, ref} from "vue";
import { elMessage, useElement } from '@/hooks/use-element'
import type { FormInstance, FormRules } from 'element-plus'
import {registerReq} from "@/api/user";
const formRules = useElement().formRules
let user = reactive({
  name: '',
  addr: '',
  hobby: [],
  sex: '',
})
const refUserForm = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  console.log(formEl);
  await formEl.validate((valid, fields) => {
    console.log(valid,fields)
    if (valid) {
      registerFunc()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const registerFunc=()=>{
  console.log('submit!')
  registerReq(user)
      .then(data=>{
    console.log("注册成功");
    elMessage('注册成功')
  },(err)=>{

        console.log(err);
      })
}

</script>

<style scoped>
.user-form {
  width: 360px;
}
</style>
